<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.teamName" placeholder="社团名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" @focus="clearData()">
        <el-option v-for="item in teamList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
        <el-select v-model="listQuery.deptId" class="filter-item" placeholder="部门名称" @focus="teamchange()">
          <el-option v-for="item in deptList" :key="item.id" :label="item.name" :value="item.name" />
        </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        高级查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增干部
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="系统编号" sortable="custom" align="center" width="100" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户姓名" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="真实姓名" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.realname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.sex }}</span>
        </template>
      </el-table-column>
      <el-table-column label="职位" width="150px" align="center">
        <template slot-scope="{row}">
          <span v-if="row.job==1">部长</span>
          <span v-if="row.job==0">干事</span>
        </template>
      </el-table-column>
      <el-table-column label="电话" width="250px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.tel }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" width="250px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属社团" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.teamName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属部门" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.dept }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>

          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="用户姓名">
          <el-input v-model="temp.username" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="temp.realname" />
        </el-form-item>

        <el-form-item label="用户性别">
          <el-radio v-model="temp.sex" label="男">男</el-radio>
          <el-radio v-model="temp.sex" label="女">女</el-radio>
        </el-form-item>

        <el-form-item label="电话">
          <el-input v-model="temp.tel" />
        </el-form-item>

        <el-form-item label="密码">
          <el-input v-model="temp.password" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="temp.email" />
        </el-form-item>
        <el-form-item label="社团名称">
          <el-select v-model="listQuery.teamName" placeholder="社团名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" >
            <el-option v-for="item in teamList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门名称">
          <el-select v-model="listQuery.deptId" class="filter-item" placeholder="部门名称" @focus="teamchange()">
            <el-option v-for="item in deptList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户职位">
          <el-radio v-model="temp.job" label="1">部长</el-radio>
          <el-radio v-model="temp.job" label="2">干事</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { fetchPv } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination/index.vue'
import request from '@/utils/request' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        username: undefined,
        tel: undefined,
        teamName: '',
        deptId: ''
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      userList: [],
      teamList: [],
      deptList: [],
      temp: {
        id: undefined,
        name: '',
        desc: '',
        userId: '',
        teamName: '',
        deptId: ''
      },
      temp2: {
        password: '',
        password2: ''
      },
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogStatus: '',
      textMap: {
        update: '在线编辑',
        create: '添加干部'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    this.getUserList()
    this.getTeamList()
  },
  methods: {
    clearData() {
      this.deptList = []
    },
    teamchange() {
      request({
        url: 'dept/deptlistByTeamId?teamName=' + this.listQuery.teamName,
        method: 'get'
      }).then(res => {
        if (res.code === 20000) {
          this.deptList = res.data
          this.total = res.total
        }
      })
    },
    getTeamList() {
      request(
        {
          url: 'http://localhost:9999/team/queryTeamList',
          method: 'get'
        }).then(res => {
        if (res.code === 20000) {
          this.teamList = res.data
        }
      })
    },
    getUserList() {
      request(
        {
          url: 'http://localhost:9999/teamuser/queryTeamUserList',
          method: 'get'
        }).then(res => {
        if (res.code === 20000) {
          this.userList = res.data
        }
      })
    },
    getList() {
      this.listLoading = true
      request({
        url: 'teamuser/queryTeamUserList',
        method: 'get',
        params: this.listQuery
      }).then(res => {
        this.listLoading = false
        this.list = res.data
        this.total = res.total
      })
      // fetchList(this.listQuery).then(response => {
      //   this.list = response.data.items
      //   this.total = response.data.total
      //
      //   // Just to simulate the time of the request
      //   setTimeout(() => {
      //     this.listLoading = false
      //   }, 1.5 * 1000)
      // })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        status: 0,
        username: undefined,
        sex: undefined,
        tel: undefined,
        email: undefined,
        type: undefined,
        realname: undefined
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCreate2(row) {
      this.dialogFormVisible2 = true
      this.temp2.id = row.id
    },
    createData() {
      /**
       * 1获取信息
       * 2提交数据信息
       * 3获取后端接口返回的状态码
       * 4如果成功 重新加载table 让显示最新的数据 同时form窗口隐藏
       * */

      this.temp.deptId = this.listQuery.deptId
      this.temp.teamName = this.listQuery.teamName
      request.post('teamuser/addInfo', this.temp).then(res => {
        if (res.code === 20000) {
          // 关闭弹出框
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: '添加成功',
            type: 'success',
            duration: 2000
          })
          this.listQuery = ''
          this.getList()
        }
      })

      // this.$refs['dataForm'].validate((valid) => {
      //   if (valid) {
      //     this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
      //     this.temp.author = 'vue-element-admin'
      //     createArticle(this.temp).then(() => {
      //       this.list.unshift(this.temp)
      //       this.dialogFormVisible = false
      //       this.$notify({
      //         title: 'Success',
      //         message: 'Created Successfully',
      //         type: 'success',
      //         duration: 2000
      //       })
      //     })
      //   }
      // })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      // 吧数据类型转换成一致 type
      this.temp.type = String(row.type)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.temp.teamName = this.listQuery.teamName
      this.temp.deptId = this.listQuery.deptId
      /**
       * 1获取信息 注意id
       * 2吧获取到的内容 同各国修改接口传入到后端服务器
       * 3根据后端返回结果集
       * 如果成功 重新加载table 关闭form单
       * */
      request.post('teamuser/updateInfo', this.temp).then(res => {
        if (res.code === 20000) {
          // 关闭弹出框
          this.dialogFormVisible = false
          this.$notify({
            title: 'True',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        } else {
          this.$notify({
            title: 'False',
            message: '修改失败',
            type: 'fail',
            duration: 2000
          })
        }
      })
      this.listQuery.teamName = ''
      this.listQuery.deptId = ''
      // this.$refs['dataForm'].validate((valid) => {
      //   if (valid) {
      //     const tempData = Object.assign({}, this.temp)
      //     tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
      //     updateArticle(tempData).then(() => {
      //       const index = this.list.findIndex(v => v.id === this.temp.id)
      //       this.list.splice(index, 1, this.temp)
      //       this.dialogFormVisible = false
      //       this.$notify({
      //         title: 'Success',
      //         message: 'Update Successfully',
      //         type: 'success',
      //         duration: 2000
      //       })
      //     })
      //   }
      // })
    },
    handleDelete(row, index) {
      /**
       *1获取要删除记录的id 主键
       * 2发送请求给后端服务器
       * 3前后端根据后端服务器返回结果判断是否成功
       * 4成功的话 重新加载table  展示最新内容
       */
      request('teamuser/deleteById?id=' + row.id).then(res => {
        if (res.code === 20000) {
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        }
      })

      // this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
